import groovy.sql.Sql;
import test.Test2;
import org.springframework.web.servlet.support.RequestContextUtils as RCU;
import grails.util.GrailsUtil;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler;
import org.codehaus.groovy.grails.web.converters.ConverterUtil; 
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;

class MyTestController 
{
	def dataSource;
	def jdbcTmplt;
	def utilService;

	static allowedMethods = [delete:'POST', save:'POST', update:'POST']
	def index = {}
	
	def divPage = {}
	
	def pageTest = {}
	
	def goFunc = {}
	
	def testFlashMessage = 
	{
		flash.message = "I am flash message.";
		redirect(action:pageTest)
	}
	
	def sss = 
	{
		def aaa = params.aaa;
		log.info(aaa);
		render(text:"${aaa}", contentType:'text/html', encoding:'UTF-8');
	}
	
	def test = 
	{
		def list = Person.executeQuery("select id, name from Person");
		list.each
		{
			println it[0]+" "+it[1];
		}
		params.aaa = "测试params传递";
		//redirect(action:'sss', params:[aaa:'测试params传递'])
		redirect(action:'sss', params:params)
	}	
	
	
	////////////////////////////////////test upload
	def uploadPage = {}
	def uploadTest = 
	{
		def file = request.getFile("myFile");
		def fileName = file.getOriginalFilename();
		def fileSize = file.size;
		def isEmpty = file.isEmpty();
		println "fileName:${fileName}  fileSize:${fileSize}  isEmpty:${isEmpty}"
		if(file && !file.empty && file.size<1024*1024)
		{
			def realPath = session.getServletContext().getRealPath("");
			file.transferTo(new File("${realPath}/upload/${fileName}"))
			return render(text:'成功', contentType:'text/html', encoding:'UTF-8');			
		}
		
		render(text:'失败', contentType:'text/html', encoding:'UTF-8');          //text/plaintext
	}
	
	//////////////////////////////////test message resource
	def testMessage = 
	{
		//this properties from conf/config.groovy. 
		def msg100 = grailsApplication.config.aaa.bbb;
		println msg100;
		
		//this message from i18n
		def messageSource = grailsAttributes.getApplicationContext().getBean("messageSource");
		def locale = RCU.getLocale(request)
		def msgInfo = messageSource.getMessage("default.paginate.prev", null, "aaa", locale);
		println msgInfo;
		
		//this message from conf/sss.properties. which is created by me.
		Properties props = new Properties();
		println "${this.getClass()}";
		props.load(this.getClass().getResourceAsStream("sss.properties"));
		String myName = props.getProperty("myName");
		myName = new String(myName.getBytes("ISO-8859-1"),"UTF-8")
		println myName;
		
		render (text:"from i18n message is:${msgInfo}<br> from conf/sss.properties message is:${myName}", contentType:'text/html', encoding:'UTF-8')
	}
	
	////////////////////////////////////test tag
	def testTag = 
	{
		def myList = [];
		myList << [1, "aaa"]
		myList << [2, "bbb"]
		myList << [3, "ccc"]
		myList << [4, "ddd"]
		myList << [5, "eee"]
	}
	
	///////////////////////////////////test groovy sql
	def gsqlTest = 
	{
		def lst = [];
		def gsql = new Sql(dataSource);
		gsql.eachRow("select id,name from PERSON") { println it[0]+":"+it[1] };

		render "success"
	}
	
	//////////////////////////////////test transaction
	def transTest = 
	{
		def msg = ""
		Person.withTransaction
		{
			tx->
			try
			{
				jdbcTmplt.update("update person set age=50 where id=1");
				jdbcTmplt.update("update author set name='Tom2' where id=1");
				render(text:'success')
			}catch(Exception e)
			{
				tx.setRollbackOnly();
				println e.getMessage();
				render(text:'failure')
			}
		}
	}
	
	/////////////////////////////////////a1 page
	def a1 = 
	{
			def func = Funcinfo.findAll("from Funcinfo");

			def list = [];
			for(i in 1..100)
			{
				list << ['测试1','grails'];
			}
			def str = "";
			list.each
			{
				str += it[0]+":"+it[1]+",";
			}
			
			return [str:str, func:func]
	}
	
	//////////////////////////////////////验证码
	def randomImage = 
	{
			int fc = 200;
			int bc = 250;
		    Random random2 = new Random();
		        
		    if(fc>255) fc=255;
		    if(bc>255) bc=255;
		    int rr=fc+random2.nextInt(bc-fc);
		    int gg=fc+random2.nextInt(bc-fc);
		    int bb=fc+random2.nextInt(bc-fc);
		    def color1 =  new Color(rr,gg,bb);
		        
		    fc = 160;
		    bc = 200;
		    rr=fc+random2.nextInt(bc-fc);
		    gg=fc+random2.nextInt(bc-fc);
		    bb=fc+random2.nextInt(bc-fc);
		    def color2 =  new Color(rr,gg,bb);

			//设置内容类型及页面不缓存
			response.setContentType("image/jpeg");
			response.setHeader("Pragma","No-cache");
			response.setHeader("Cache-Control","no-cache");
			response.setDateHeader("Expires", 0);
			
			// 在内存中创建图象
			int width=60, height=20;
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			
			// 获取图形上下文
			Graphics g = image.getGraphics();
			
			//生成随机类
			Random random = new Random();
			
			// 设定背景色
			g.setColor(color1);
			g.fillRect(0, 0, width, height);
			
			//设定字体
			g.setFont(new Font("Times New Roman",Font.PLAIN,18));
			
			//画边框
			//g.setColor(Color.BLACK);
			//g.drawRect(0,0,width-1,height-1);
			
			// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
			g.setColor(color2);
			for (i in 0..<155)
			{
				int x = random.nextInt(width);
			    int y = random.nextInt(height);
			    int xl = random.nextInt(12);
			    int yl = random.nextInt(12);
			    g.drawLine(x,y,x+xl,y+yl);
			}
			
			//随机产生4位字符的认证码
			String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
			char [] randStr = new char[4];
			for(int i=0; i<4; i++)
			{
				int rand = (int)(Math.random() * 36);
				randStr[i] = chars.charAt(rand);
			} 
			String randCode = new String(randStr);
			
			for (i in 0..<randCode.length()){
			    String rand=String.valueOf(randCode.substring(i,i+1));
			    // 将验证码显示到图象中
			    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			    g.drawString(rand,13*i+6,16);
			}
			
			// 将验证码存入session
			request.setAttribute("randCode",randCode);
				
			// 图象生效
			g.dispose();
			
			// 输出图象到页面
			ImageIO.write(image, "JPEG",response.getOutputStream());	

	}

	/////////////////////////////////////强制下载
	def forceDown = {}
	
	/////////////////////////////////////编码
	def doEncodingTest = 
	{
		def str = params.flag;
		println str;
		
		def str3 = "题库";
		str3 = URLEncoder.encode(str3);
		println str3;
		str3 = URLDecoder.decode(str3);
		println str3;
		render(view:'encodingTest');
	}
	
	//////////////////////////////////////GroovyShell
	def groovyShell = 
	{
		def input;
		try
		{
			input = servletContext.getResourceAsStream("/WEB-INF/myScript.groovy");
			def result = new GroovyShell().evaluate(input.text);
			render result;
		}finally
		{
			input.close();
		}
	}
	
	///////////////////////////////////////ApplicationContext
	def appCtx = 
	{
		def conn = grailsAttributes.getApplicationContext().getBean("dataSource").getConnection();
		println conn;
		render (conn)
	}
	
	///////////////////////////////////////fckeditor2.5
	def fck = 
	{
			
	}	
	def doFck = 
	{
		def content = params.content;
		//println content;
		render(text:"${content}", contentType:'text/html', encoding:'UTF-8');   
	}
	
	////////////////////////////////////////config value
	def goConfig = 
	{
		def encodeStr =  grailsApplication.config.grails.views.gsp.encoding;
		
		def username = grailsApplication.config.dataSource.username  
		def password = grailsApplication.config.dataSource.password  
		def databaseUrl = grailsApplication.config.dataSource.url  
		def driver = grailsApplication.config.dataSource.driverClassName 
		def str = "${encodeStr}<br>${username} | ${password} | ${databaseUrl} | ${driver}"
		render (str);
	}
	
	////////////////////////////////////////GrailsUtil
	def goGrailsUtil = 
	{
		def str = "";
		switch(GrailsUtil.environment) 
		{
			case "production":
				str = "production";
				break;
			case "development":
				str = "development";
				break;
			default:
				str = "no environment";
		}
		
		render str;
	}
	
	/////////////////////////////////////////template
	def goTemplate = {}
	
	////////////////////////////////////////ModelAndView
	def modelView = 
	{
		List list = [];
		list << "aaa";
		list << "bbb";
		return new ModelAndView("/mytest/modelView", [list:list])
	}
	
	//////////////////////////////////////
	def testCharset2 = 
	{
		println "--------------------------------"
		Enumeration e = request.getHeaderNames();
	  	while (e.hasMoreElements()) 
	  	{
		    String name = (String)e.nextElement();
		    String value = request.getHeader(name);
		    println( name+" : "+value);
	    }
	  	println "--------------------------------"
	  	
		String flag = params.flag;
		println flag;

		render "${flag}";
	}
	
	/////////////////////////////////////test hidden var
	def testHiddenVar=
	{
		def realPath = servletContext.getRealPath("");
		render realPath;
	}
	
	////////////////////////////////////test JdbcTemplate
	def testJT=
	{
		def personCount = jdbcTmplt.queryForInt("select count(*) from Person");
		render personCount;
	}
	
	///////////////////////////////////GrailsDomainClass
	def grailsDomainClass = 
	{
		//GrailsDomainClass domainClass = (GrailsDomainClass)grailsApplication.getArtefact(DomainClassArtefactHandler.TYPE,"Person")
		GrailsDomainClass domainClass = ConverterUtil.getDomainClass("Person"); 
		def proplist;
		if (domainClass != null) 
		{  
			proplist = domainClass.getPersistentProperties() 
		}
		proplist.each
		{
			println it?.name +":"+it?.type;
		}
		println "------------------------------------"
		render "ok"
	}
	
	//////////////////////////////////log4j test
	def log4jtest=
	{
		log.error("lxh log4j test");
		render "lxh log4j test"
	}

}